package cn.itcast.hotel.service.impl;

import cn.itcast.hotel.dto.PageResult;
import cn.itcast.hotel.dto.RequestParams;
import cn.itcast.hotel.mapper.HotelMapper;
import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.service.IHotelService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;


import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;


@Service
@Slf4j
public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {
    @Autowired
    private RestHighLevelClient client;
    /**
     * 搜索酒店数据
     *
     * @param params
     * @return
     */
    @Override
    public PageResult search(RequestParams params) {
        //创建请求
        SearchRequest request =new SearchRequest("hotel");
        //过滤条件搜索函数封装
        buildBasicQuery(params,request);
        //分页
        int page = params.getPage();
        int size = params.getSize();
        request.source().from((page-1)*size).size(size);
        // 2.3.排序
        String location = params.getLocation();
        if (location != null && !location.equals("")) {
            request.source().sort(SortBuilders
                    .geoDistanceSort("location", new GeoPoint(location))
                    .order(SortOrder.ASC)
                    .unit(DistanceUnit.KILOMETERS)
            );
        }
        //设置高亮, 三要素: 字段,前缀(<em>),后缀(</em>)
        request.source().highlighter(
                SearchSourceBuilder.highlight()
                        .field("brand")
                        .requireFieldMatch(false)
                        );

        //价格排序
        request.source().sort("price",SortOrder.DESC);
        //发送请求
        try {
            SearchResponse response = client.search(request ,RequestOptions.DEFAULT);
            //获取总条数
            long total = response.getHits().getTotalHits().value;
            //获取文档数组
            ArrayList<HotelDoc> hotelDocs = new ArrayList<>();
            SearchHit[] hits = response.getHits().getHits();
            //遍历文档数组
            for (SearchHit hit : hits) {
                String json = hit.getSourceAsString();//获取到json数据
             HotelDoc hotelDoc = JSON.parseObject(json,HotelDoc.class);//得到hoteldoc数据
                // 获取高亮结果
                Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                HighlightField highlightField = highlightFields.get("brand");
                if (highlightField != null) {
                    Text[] fragments = highlightField.getFragments();
                    if (fragments != null && fragments.length > 0) {
                        String highName = StringUtils.join(fragments);
                        if (StringUtils.isNotBlank(highName)) {
                            hotelDoc.setBrand(highName);
                        }
                        for (Text fragment : fragments) {
                            System.out.println("高亮的信息： "+fragment);
                        }
                    }

                }
                //获取排序值
                Object[] sortValues = hit.getSortValues();
                //判断
                if (sortValues.length>0){
                    Object sortValue= sortValues[0];
                    hotelDoc.setDistance(sortValue);
                }
                hotelDocs.add(hotelDoc);
            }
            return PageResult.builder().total(total).hotels(hotelDocs).build();
        } catch (IOException e) {
            log.error("search error message :{}",e.getMessage());
        }
        //解析响应
        return new PageResult();
    }

    /**
     * 过滤条件实现
     * @param params
     * @param request
     */
    private void buildBasicQuery(RequestParams params, SearchRequest request) {
        //构造查询条件
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //输入框
        String key = params.getKey();
        //判断key是否存在
        if (StringUtils.isNotBlank(key)){
            boolQuery.must(QueryBuilders.matchQuery("all",key));
        }else{
            boolQuery.must(QueryBuilders.matchAllQuery());
        }
        //过滤实现
        //城市
        if (params.getCity()!=null && !params.getCity().equals("")){
            boolQuery.filter(QueryBuilders.termQuery("city",params.getCity()));
        }
        //品牌条件
        if (params.getBrand()!=null && !params.getBrand().equals("")){
            boolQuery.filter(QueryBuilders.termQuery("brand",params.getBrand()));
        }
        //星级条件
        if (params.getStarName() != null && !params.getStarName().equals("")) {
            boolQuery.filter(QueryBuilders.termQuery("starName", params.getStarName()));
        }
        //价格
        if (params.getMinPrice()!=null && params.getMaxPrice()!=null){
            boolQuery.filter(QueryBuilders.rangeQuery("price")
                    .gte(params.getMinPrice())
                    .lte(params.getMaxPrice()));
        }
        //算分控制
        FunctionScoreQueryBuilder functionScoreQuery =
                QueryBuilders.functionScoreQuery(
                        // 原始查询，相关性算分的查询
                        boolQuery,
                        // function score的数组
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                                // 其中的一个function score 元素
                                new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                        // 过滤条件
                                        QueryBuilders.termQuery("isAD", true),
                                        // 算分函数
                                        ScoreFunctionBuilders.weightFactorFunction(10)
                                )
                        });
        request.source().query(functionScoreQuery);
    }

}